<?php
/**
 * 公共返回方法
 * Author: JiaMeng <666@majiameng.com>
 * Date: 2017/11/23
 * Time: 17:38
 */
namespace App\Services;

use tinymeng\tools\FileTool;
use tinymeng\tools\Tool;
use \App\Models\BaseModel;

class CommonServices
{

    /**
     * 记录日志文件
     * @Author: TinyMeng <666@majiameng.com>
     * @param $message
     * @param string $log_name
     * @param \Exception|null $exception
     * @return bool
     */
    static public function writeLog($message,$log_name="log",\Exception $exception = null){
        return FileTool::writeLog($message,$log_name, false,$exception);
    }


    /**
     * 获取时间戳(13位精确到豪妙)
     * @Author: TinyMeng <666@majiameng.com>
     * @param null $time
     * @return int
     */
    static public function millisecond($time = null) :int{
        if(empty($time)){
            list($msec, $sec) = explode(' ', microtime());
            $millisecond = (int)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        }else{
            $millisecond = strtotime($time)."000";
        }
        return (int)$millisecond;
    }


    /**
     * 获取顶级域名
     * @Author: TinyMeng <666@majiameng.com>
     * @param $url
     * @return string
     */
    static public function getTopDomain($url){
        $url = strtolower($url);  //首先转成小写
        $hosts = parse_url($url);
        if(empty($hosts['host'])){
            $url = "https://".$url;
            $hosts = parse_url($url);
        }
        $host = $hosts['host'];
        //查看是几级域名
        $data = explode('.', $host);
        $n = count($data);
        //判断是否是双后缀
        $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
        if(($n > 2) && preg_match($preg,$host)){
            //双后缀取后3位
            $host = $data[$n-3].'.'.$data[$n-2].'.'.$data[$n-1];
        }else{
            //非双后缀取后两位
            $host = $data[$n-2].'.'.$data[$n-1];
        }
        return $host;
    }


    /**
     * long int转为string
     * @Author: TinyMeng <666@majiameng.com>
     * @param $data
     */
    static public function longIntToStr(&$data){
        if(is_object($data) && ($data instanceof BaseModel)){
            $data = $data->toArray();
        }elseif(is_string($data)){
            return;
        }
        foreach ($data as $key=>&$val){
            if(is_object($val) && ($val instanceof BaseModel)){
                $val = $val->toArray();
            }
            if((is_array($val) || is_object($val)) && !empty($val)){
                self::longIntToStr($val);
            }elseif(is_int($val) && strlen($val) > 11){
                settype($val,'string');
            }
        }
    }

    /**
     * Description:  时间转换
     * Author: JiaMeng <666@majiameng.com>
     * Updater:
     * @param string $date 时间
     * @param bool $is_timestamp   是否是时间戳
     * @return false|string
     */
    public static function formatTime($date,$is_timestamp=false){
        if($is_timestamp == true){
            $time = $date;
        }else{
            $time = strtotime($date);//时间转换为时间戳
        }

        if($time >= NOW_TIME){
            return '刚刚';
        }
        $seconds = NOW_TIME - $time;
        if($seconds <= 60){
            return '刚刚';
        }
        $minutes = intval($seconds / 60);
        if($minutes <= 60){
            return $minutes.'分钟前';
        }
        $hours = intval($minutes / 60);
        if($hours <= 24){
            return $hours.'小时前';
        }
        $days = intval($hours / 24);
        if($days <= 7){
            return $days.'天前';
        }
        $weeks = intval($days / 7 );
        if($weeks <= 4){
            return $weeks.'周前';
        }
        $months = intval($weeks / 4 );
        if($months <= 12){
            return $months.'月前';
        }
        $years = intval($months / 12 );
        if($years <= 3){
            return $years.'年前';
        }
        return date('Y-m-d',$time);
    }


    /**
     * Description:将秒数转换为00:00:00(时分秒格式）
     * Param:参数说明
     * [in] $times int n秒
     * Return:返回值
     * 00:00:00（时分秒）
     */
    public static function formatTimeBySecond($times=0)
    {
        $result = '00:00:00';
        if ($times>0){
            $hour = floor($times/3600);
            $minute = floor($times%3600/60);
            $second = floor(($times-60 * $minute) % 60);
            if ($hour < 10) {
                $hour = '0' . $hour;
            }
            if($minute<10){
                $minute = "0".$minute;
            }
            if($second<10){
                $second = "0".$second;
            }
            $result = $hour.':'.$minute.':'.$second;
        }
        return $result;
    }

    /**
     * 获取ip
     * @return mixed|string
     * @author: tinymeng <666@majiameng.com>
     * @ctime:  2021/7/20 19:32
     */
    static public function ip(){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            //获取负载均衡后用户的ip
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }else{
            $ip = request()->ip();
        }
        return $ip;
    }

    /**
     * 获取用户设备
     * @return mixed|string
     * @author: tinymeng <666@majiameng.com>
     * @ctime:  2021/7/20 19:32
     */
    static public function userAgent(){
        if(isset($_SERVER['HTTP_USER_AGENT'])){
            //获取负载均衡后用户的ip
            $userAgent = $_SERVER['HTTP_USER_AGENT'];
        }else{
            $userAgent = "";
        }
        return $userAgent;
    }

    /**
     * 用户设备浏览器是否支持直播
     * @author: Tinymeng <666@majiameng.com>
     * @time: 2022/4/20 16:55
     */
    static public function userAgentLive(){
        $flag = false;
        if(Tool::isWeiXin()){
            $flag = false;
        }else{
            $userAgent = self::userAgent();
            if(strpos(strtolower($userAgent),'chrome') !== false){
                $flag = true;
            }
        }
        return $flag;
    }

    /**
     * 获取url中文件名
     * @param $url
     * @author: Tinymeng <666@majiameng.com>
     * @time: 2022/4/14 19:55
     */
    static public function getUrlFilename($url,$separator = null){
        if($separator === null){
            $separator = DIRECTORY_SEPARATOR;
        }
        return substr( $url , strrpos($url , $separator)+1 );
    }

    /**
     * 获取url中文件名
     * @param $url
     * @author: Tinymeng <666@majiameng.com>
     * @time: 2022/4/14 19:55
     */
    static public function getFileSuffix($url){
        return substr( $url , strrpos($url , '.')+1 );
    }
    /**
     * 保护手机号隐私
     * @param $mobile
     * @return array|string|string[]
     */
    static public function protectMobile($mobile){
        return empty($mobile) ? '' : substr_replace($mobile,'****',3,4);
    }

    /**
     * 根据身份证号获取生日
     * @param $idCard
     * @return false|string
     */
    static public function getBirthdayByIdCard($idCard){
        $regx = '#^\d{6}(\d{4})(\d{2})(\d{2})\d{3}[0-9X]$#';
        if (!preg_match($regx, $idCard, $matches)) {
            return false;
        }
        array_shift($matches);
        list($year, $month, $day) = $matches;
        return $year.$month.$day;
    }

    /**
     * 过滤emoji字符
     * @param $str
     * @return string|string[]|null
     * @author: tinymeng <666@majiameng.com>
     * @ctime:  2021/4/30 16:22
     */
    static public function filterEmoji($str){
        $str = preg_replace_callback('/./u', function (array $match) {
            return strlen($match[0]) >= 4 ? mt_rand(10,100) : $match[0];
        }, $str);

        return $str;
    }

    /**
     * 获取服务天数
     * serviceDays
     * @param int $start_time 开始时间（时间戳）
     * @param int $end_time 结束时间（时间戳）
     * @return float 服务天数
     * @author: Tinymeng <666@majiameng.com>
     * @time: 2022/8/19 17:52
     */
    static public function serviceDays($start_time,$end_time){
        $service_day = 0;//服务天数
        $service_time = $end_time - $start_time;//相差秒数
        if($service_time > 0){
            //计算服务天数
            $service_day = floor($service_time/(60*60*24));
            //去除正数天的余数（秒）
            $remainder = $service_time % (60*60*24);
            if($remainder !== 0){
                //去除正数天是否够半天
                if($remainder > 60*60*12){
                    $service_day += 1;
                }else{
                    $service_day += 0.5;
                }
            }
        }
        return $service_day;
    }

    /**
     * @param $datetime
     * @return \DateTime
     * @throws \Exception
     */
    static public function dateTimeSetZone($datetime)
    {
        $dateTime = new \DateTime($datetime);
        $dateTime->setTimezone(new \DateTimeZone(config('app.timezone')));
        return $dateTime;
    }
}
